<?php

namespace app\common\service\product;

use app\common\base\BaseService;

/**
 * Class LockService 锁仓
 * @package app\common\service\product
 * @author wangshenghong
 * @date 2024.03.01
 */
class LockService extends BaseService {

    /**
     * 获取搜索油品的选项
     */
    public function searchOption(){
        //1、油品筛选、2、库存筛选、3、价格筛选
        //1、油品筛选
        $where = [
            ['status', '=', OilEnum::STATUS_NORMAL],
            ['is_delete', '=', OilEnum::DELETE_FALSE],
        ];
        $field = 'name,`id` as `key`,model';
        $oilList = Oil::field($field)->where($where)->order('sort desc')->select()->toArray();
        foreach ($oilList as &$item) {
            $item['name'] = $item['name'] . "（{$item['model']}）";
            unset($item['model']);
        }
        array_unshift($oilList, ['name' => '默认筛选', 'key' => '0']);
        //2、库存筛选
        $stock = $this->getSearchStock();
        //3、价格筛选
        $price = $this->getSearchPrice();
        $result = [
            'model' => $oilList,
            'stock' => $stock,
            'price' => $price
        ];
        return $result;
    }

    /**
     * 获取库存的筛选条件
     *
     * @return array
     */
    public function getSearchStock(){
        $stock = [
            ['name' => '默认筛选', 'key' => 0, 'mark' => ''],
            ['name' => '0-50', 'key' => 1, 'mark' => '0-50'],
            ['name' => '50-100',  'key' => 2, 'mark' => '50-100'],
            ['name' => '100以上',  'key' => 3, 'mark' => '100'],
        ];
        return $stock;
    }

    /**
     * 获取价格的筛选条件
     *
     * @return array
     */
    public function getSearchPrice(){
        $price = [
            ['name' => '默认筛选', 'key' => 0],
            ['name' => '价格升序', 'key' => 1],
            ['name' => '价格降序', 'key' => 2],

        ];
        return $price;
    }

    /**
     * 获取锁仓油品列表数据
     *
     * @param string $model         油品型号筛选（油品ID）
     * @param string $stock         库存筛选
     * @param string $price         价格筛选
     * @param int    $page          页码
     * @param int    $limit         每页条数
     * @return array
     */
    public function lists($model = '', $stock = '', $price = '', $page = 1, $limit = 10){
        $field = 'id,type,name,oil_id,model,open_price,current_price,buy_price,stock,overnight_fee,hold_time,deadline,create_time';
        $where = [
            ['stock', '>', 0],
            ['is_shelves', '=', 1]
        ];
        $list = Lock::field($field)->withAttr('create_time',function ($value) {
            return $value;
        })
        ->where($where)
        ->where(function ($query) {
            $time = time();
            $where = [
                ['deadline', '>', $time],
                ['type', '=', LockEnum::TYPE_ADMIN_CREATE]
            ];
            $where1 = [
                ['hold_time', '>', $time],
                ['type', '=', LockEnum::TYPE_USER_BUY]
            ];
            $query->where($where)->whereOr($where1);
        });
        //油品型号筛选(型号与油品ID都是唯一标识)
        if ($model) {
            $list = $list->where('oil_id', $model);
        }
        //油品库存筛选
        if ($stock) {
            $searchStock = $this->getSearchStock();
            foreach ($searchStock as $item) {
                if ($item['key'] == $stock) {
                    if (strpos($item['mark'], '-') !== false) {
                        $mark = explode('-', $item['mark']);
                        $list = $list->whereBetween('stock', [$mark[0], $mark[1]]);
                    } else {
                        $where = [
                            ['stock', '>', $item['mark']]
                        ];
                        $list = $list->where($where);
                    }
                    break;
                }
            }
        }
        $count = $list->count();
        //价格筛选
        if ($price) {
            $sortField = $price == 1 ? 'current_price asc' : 'current_price desc';
            $list = $list->order($sortField);
        } else {
            $list = $list->order('id desc');
        }
        $list = $list->page($page, $limit)->select()->toArray();
//        echo Db::getLastSql();die;
        if ($list) {
            //获取油品列表
            $oilIds = array_unique(array_column($list, 'oil_id'));
            $field = 'id,type,model';
            $oilList = Oil::field($field)->whereIn('id', $oilIds)->select()->toArray();
            $oilList = $oilList ? array_column($oilList, null, 'id') : [];
            foreach ($list as &$item) {
                $item['oil_type'] = isset($oilList[$item['oil_id']]) ? $oilList[$item['oil_id']]['type'] : 0;
                $item['model'] = isset($oilList[$item['oil_id']]) ? $oilList[$item['oil_id']]['model'] : '';
                $item['deadline'] = date('Y-m-d H:i:s', $item['deadline']);
                $item['hold_time'] = date('m.d H:i', $item['create_time']).'-'.date('m.d H:i', $item['hold_time']);

                if ($item['type'] == LockEnum::TYPE_ADMIN_CREATE) {
                    $range = $item['current_price'] - $item['open_price'];
                } else {
                    $range = $item['current_price'] - $item['buy_price'];
                }
                $item['range'] = $range > 0 ? "+{$range}" : "$range";
                $item['range_mark'] = $range > 0 ? 1 : ($range == 0 ? 2 : 0); //0:跌，1:涨，2:不变
                //列表中隔夜费的计算！！！！！！！

                unset($item['create_time']);
            }
        }

        $result = [
            'count' => $count,
            'total_page' => ceil($count/$limit),
            'list' => $list
        ];
        return $result;
    }

    /**
     * 获取锁仓详情
     *
     * @param int $id       ID
     * @return bool|array
     */
    public function detail($id){
        if (!$id) {
            self::$errorCode = ErrorCode::LOCK_ID_NULL;
            return false;
        }

        $field = 'id,type,name,oil_id,model,open_price,current_price,buy_price,stock,overnight_fee,hold_time,deadline,create_time,deposit_min_ratio';
        $info = Lock::field($field)->withAttr('create_time',function ($value) {
            return $value;
        })->where('id', $id)->findOrEmpty()->toArray();
        if (!$info) {
            self::$errorCode = ErrorCode::LOCK_ID_NULL;
            return false;
        }

        if ($info['type'] == LockEnum::TYPE_ADMIN_CREATE) {
            $range = $info['current_price'] - $info['open_price'];
        } else {
            $range = $info['current_price'] - $info['buy_price'];
        }
        //获取油品信息
        $field = 'id,type,model';
        $oilInfo = Oil::field($field)->where('id', $info['oil_id'])->findOrEmpty()->toArray();

        $info['deadline'] = date('Y-m-d H:i:s', $info['deadline']);
        $info['hold_time'] = date('m.d H:i', $info['create_time']).'-'.date('m.d H:i', $info['hold_time']);
        $info['range'] = $range > 0 ? "+{$range}" : "$range";
        $info['range_mark'] = $range > 0 ? 1 : ($range == 0 ? 2 : 0); //0:跌，1:涨，2:不变
        $info['oil_type'] = $oilInfo ? $oilInfo['type'] : 0;
        $info['model'] = $oilInfo ? $oilInfo['model'] : $info['model'];
        $info['deposit_min_ratio'] = $info['deposit_min_ratio'] . '%';
        unset($info['create_time']);

        return $info;
    }

    /**
     * 确认锁仓
     *
     * @param $uid
     * @param $lockId
     * @param $oilId
     * @param $depositRatio
     * @param $buyNum
     * @param $currentPrice
     * @return bool
     */
    public function create($uid, $lockId, $oilId, $depositRatio, $buyNum, $currentPrice) {
        if (!$uid) {
            self::$errorCode = ErrorCode::TOKEN_ERROR;
            return false;
        }

        $where = [
            ['uid', '=', $uid],
            ['selected', '=', 1],
        ];
        $field = 'id,amount_lock,name,mobile';
        $company = Company::field($field)->where($where)->findOrEmpty()->toArray();
        if (!$company) {
            self::$errorCode = ErrorCode::COMPANY_NOT_EXIST;
            return false;
        }
        $companyId = $company['id'];
        if (!$lockId) {
            self::$errorCode = ErrorCode::LOCK_ID_NULL;
            return false;
        }
        //获取锁仓信息
        $field = 'id,type,uid,company_id,current_price,stock,deposit_min_ratio,hold_time,overnight_fee,lock_order_id';
        $lockInfo = Lock::field($field)->where('id', $lockId)->findOrEmpty()->toArray();
        if (!$lockInfo) {
            self::$errorCode = ErrorCode::LOCK_NOT_EXIST;
            return false;
        }

        $oilInfo = Oil::field('id')->where('id', $oilId)->findOrEmpty()->toArray();
        if (!$oilInfo) {
            self::$errorCode = ErrorCode::OIL_NOT_EXIST;
            return false;
        }
        if ($buyNum < 0) {
            self::$errorCode = ErrorCode::OIL_BUY_NUM_ERROR;
            return false;
        }
        //校验库存
        if ($lockInfo['stock'] < $buyNum) {
            self::$errorCode = ErrorCode::OIL_STOCK_NOT_ENOUGH;
            return false;
        }
        //判断价格是否有变动
        if ($currentPrice != $lockInfo['current_price']) {
            self::$errorCode = ErrorCode::OIL_PRICE_CHANGE;
            return false;
        }
        //判断保证金缴纳的比例
        if ($depositRatio < $lockInfo['deposit_min_ratio']) {
            self::$errorCode = ErrorCode::LOCK_DEPOSIT_ERROR;
            return false;
        }
        //判断账号余额
        $totalPay = ($buyNum * $currentPrice)*($depositRatio / 100);
        if ($totalPay > $company['amount_lock']) {
            self::$errorCode = ErrorCode::COMPANY_AMOUNT_NOT_ENOUGH;
            return false;
        }

        $time = time();
        $outTradeNo = date('YmdHis') . substr($uid*($time-946656000),4,5).mt_rand(1000,9999);

        Db::startTrans();
        //所有参数校验通过，则生成订单
        try {
            //1、生成订单 2、扣减库存 3、扣减账户的保证金金额 4、添加到账号余额明细里
            //1、生成订单
            $orderData = [
                'out_trade_no' => $outTradeNo,
                'company_id' => $companyId,
                'company_name' => $company['name'],
                'company_mobile' => $company['mobile'],
                'uid' => $uid,
                'be_uid' => $lockInfo['uid'],
                'be_company_id' => $lockInfo['company_id'],
                'lock_id' => $lockId,
                'oil_id' => $oilId,
                'price' => $currentPrice,
                'stock' => $buyNum,
                'buy_number' => $buyNum,
                'total_price' => bcmul($currentPrice, $buyNum, 2),
                'deposit_ratio' => $depositRatio,
                'overnight_fee' => $lockInfo['overnight_fee'],
                'hold_time' => $lockInfo['hold_time'],
                'status_lock' => OrderEnum::STATUS_LOCK_HOLD,
                'create_time' => $time
            ];
            LockOrder::create($orderData);
            //2、扣减库存
            Lock::where('id', $lockId)->dec('stock', $buyNum)->update();
            //2A、如果是用户的持仓，则扣减持仓的库存
            if ($lockInfo['type'] == LockEnum::TYPE_USER_BUY) {
                $lockOrderId = $lockInfo['lock_order_id'];
                LockOrder::where('id', $lockOrderId)->dec('stock', $buyNum)->update();
            }

            //3、扣减账户的保证金金额
            Company::where('id', $companyId)->dec('amount_lock', $totalPay)->update();

            //4、添加到账号余额明细里
            $data = [
                'uid' => $uid,
                'company_id' => $companyId,
                'company_name' => $company['name'],
                'company_mobile' => $company['mobile'],
                'amount' => $totalPay,
                'way' => CompanyEnum::WAY_COMPANY,
                'type' => CompanyEnum::BUSINESS_TYPE_LOCK,
                'channel' => CompanyEnum::CHANNEL_EXPEND,
                'status' => CompanyEnum::AMOUNT_STATUS_SUCCESS,
                'create_time' => time(),
            ];
            UserAccountRecord::create($data);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::$errorCode = ErrorCode::USER_OFFICIAL_ADD_FAIL;
            return false;
        }
    }

    /**
     *  获取持仓中、交易中列表
     *
     * @param $uid
     * @param $companyId
     * @param $type
     * @param $page
     * @param $limit
     * @return bool|array
     */
    public function buyList($uid, $type, $page, $limit){
        if (!$uid) {
            self::$errorCode = ErrorCode::TOKEN_ERROR;
            return false;
        }
        $where = [
            ['uid', '=', $uid],
            ['selected', '=', 1],
        ];
        $field = 'id,amount_lock';
        $company = Company::field($field)->where($where)->findOrEmpty()->toArray();
        if (!$company) {
            self::$errorCode = ErrorCode::COMPANY_NOT_EXIST;
            return false;
        }
        $companyId = $company['id'];

        $types = OrderEnum::getStatusLockDesc();
        if (!array_key_exists($type, $types)) {
            self::$errorCode = ErrorCode::ORDER_TYPE_ERROR;
            return false;
        }

        $where = [
            ['uid', '=', $uid],
            ['company_id', '=', $companyId],
            ['status_lock', '=', $type],
            ['stock', '>', 0],
        ];
        $field = 'id,out_trade_no,lock_id,oil_id,price buy_price,buy_number,stock,total_price,deposit_ratio,hold_time,status_lock,create_time';
        $list = LockOrder::field($field)->withAttr('create_time',function ($value) {
            return $value;
        })->where($where)->page($page, $limit)->order('id desc')->select()->toArray();
        $count = LockOrder::where($where)->count();
        if ($list) {
            //锁仓列表
            $lockIds = array_column($list, 'lock_id');
            $field = 'id,name,current_price,overnight_fee,hold_time,create_time';
            $lockList = Lock::field($field)->withAttr('create_time',function ($value) {
                return $value;
            })->whereIn('id', $lockIds)->select()->toArray();
            $lockList = $lockList ? array_column($lockList, null, 'id') : [];
            //油品列表
            $oilIds = array_column($list, 'oil_id');
            $field = 'id,model,type';
            $oilList = Oil::field($field)->whereIn('id', $oilIds)->select()->toArray();
            $oilList = $oilList ? array_column($oilList, null, 'id') : [];
            $time = time();
            foreach ($list as & $item) {
                $item['name'] = isset($lockList[$item['lock_id']]) ? $lockList[$item['lock_id']]['name'] : '';
                $item['current_price'] = isset($lockList[$item['lock_id']]) ? $lockList[$item['lock_id']]['current_price'] : '';
                $overnightFee = isset($lockList[$item['lock_id']]) ? $lockList[$item['lock_id']]['overnight_fee'] : '';
                $days = ceil(($time - $item['create_time'])/86400);
                $item['overnight_fee'] = bcmul($overnightFee, $days, 2);
                $holdTime = '';
                if (isset($lockList[$item['lock_id']])) {
                    $holdTime = date('m.d H:i', $lockList[$item['lock_id']]['create_time']) . '-' . date('m.d H:i', $lockList[$item['lock_id']]['hold_time']);
                }
                $item['hold_time'] = $holdTime;
                $item['model'] = isset($oilList[$item['oil_id']]) ? $oilList[$item['oil_id']]['model'] : '';
                $item['oil_type'] = isset($oilList[$item['oil_id']]) ? $oilList[$item['oil_id']]['type'] : '';
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                //涨跌幅
                $range = $item['current_price'] - $item['buy_price'];
                $item['range'] = $range > 0 ? "+{$range}" : "$range";
                $item['range_mark'] = $range > 0 ? 1 : ($range == 0 ? 2 : 0); //0:跌，1:涨，2:不变
                //强制提货价sprintf('%.2f', $estimateProfit);
                $item['force_price'] = bcmul($item['total_price'], (1 - (($item['deposit_ratio']/100) - 0.05)), 2);
                //已付保证金
                $item['pay_deposit'] = bcmul($item['total_price'], $item['deposit_ratio']/100, 2);
            }
        }

        $result = [
            'count' => $count,
            'total_page' => ceil($count/$limit),
            'list' => $list
        ];
        return $result;
    }

    /**
     * 锁仓提货页面信息
     *
     * @param int $uid              用户UID
     * @param int $lockOrderId      锁仓单ID
     * @return bool|array
     */
    public function pickupGoods($uid, $lockOrderId){
        if (!$uid) {
            self::$errorCode = ErrorCode::TOKEN_ERROR;
            return false;
        }
        $where = [
            ['uid', '=', $uid],
            ['selected', '=', 1],
        ];
        $field = 'id,amount_lock';
        $company = Company::field($field)->where($where)->findOrEmpty()->toArray();
        if (!$company) {
            self::$errorCode = ErrorCode::COMPANY_NOT_EXIST;
            return false;
        }
        $companyId = $company['id'];
        if (!$lockOrderId) {
            self::$errorCode = ErrorCode::LOCK_ORDER_ID_NULL;
            return false;
        }
        $field = 'id,company_id,uid,lock_id,oil_id,buy_number,stock,deposit_ratio,total_price,create_time';
        $lockOrder = LockOrder::field($field)->withAttr('create_time',function ($value) {
            return $value;
        })->where('id', $lockOrderId)->findOrEmpty()->toArray();
        if (!$lockOrder) {
            self::$errorCode = ErrorCode::LOCK_ORDER_NOT_EXIST;
            return false;
        }
        if ($lockOrder['uid'] != $uid || $lockOrder['company_id'] != $companyId) {
            self::$errorCode = ErrorCode::SERVER_PERMISSION_DENIED;
            return false;
        }
        $time = time();
        //锁仓信息
        $field = 'name,current_price,overnight_fee';
        $lockInfo = Lock::field($field)->where('id', $lockOrder['lock_id'])->findOrEmpty()->toArray();
        $lockOrder['name'] = $lockInfo ? $lockInfo['name'] : '';
        $lockOrder['current_price'] = $lockInfo ? $lockInfo['current_price'] : '';
        $days = ceil(($time - $lockOrder['create_time'])/86400);
        $lockOrder['overnight_fee'] = bcmul($lockInfo['overnight_fee'], $days, 2);
        //油品信息
        $field = 'model';
        $oilInfo = Oil::field($field)->where('id', $lockOrder['oil_id'])->findOrEmpty()->toArray();
        $lockOrder['model'] = $oilInfo ? $oilInfo['model'] : '';
        //企业账户余额
        $field = 'amount_procure,amount_lock';
        $companyInfo = Company::field($field)->where('id', $companyId)->findOrEmpty()->toArray();
        $lockOrder['company'] = $companyInfo ? $companyInfo : [];

        $lockOrder['pay_deposit'] = sprintf('%.2f', $lockOrder['total_price'] * ($lockOrder['deposit_ratio']/100));
        return  $lockOrder;
    }

    /**
     * 锁仓提货
     *
     * @param $uid
     * @param $lockOrderId
     * @param $pickupNum
     * @param $carInfo
     * @return bool|array
     */
    public function pickupGoodsPay($uid, $lockOrderId, $pickupNum, $currentPrice, $carInfo){
        if (!$uid) {
            self::$errorCode = ErrorCode::TOKEN_ERROR;
            return false;
        }
        if (!$lockOrderId) {
            self::$errorCode = ErrorCode::LOCK_ORDER_ID_NULL;
            return false;
        }
        $where = [
            ['uid', '=', $uid],
            ['selected', '=', 1],
        ];
        $field = 'id,amount_lock,amount_procure';
        $company = Company::field($field)->where($where)->findOrEmpty()->toArray();
        if (!$company) {
            self::$errorCode = ErrorCode::COMPANY_NOT_EXIST;
            return false;
        }
        $companyId = $company['id'];
        $field = 'id,buy_number,lock_id,oil_id,stock,total_price,deposit_ratio,uid';
        $lockOrder = LockOrder::field($field)->where('id', $lockOrderId)->findOrEmpty()->toArray();
        if (!$lockOrder) {
            self::$errorCode = ErrorCode::LOCK_ORDER_NOT_EXIST;
            return false;
        }
        if ($lockOrder['uid'] != $uid) {
            self::$errorCode = ErrorCode::SERVER_PERMISSION_DENIED;
            return false;
        }
        if ($lockOrder['stock'] <= 0) {
            self::$errorCode = ErrorCode::OIL_STOCK_NOT_ENOUGH;
            return false;
        }
        if ($pickupNum < 0) {
            self::$errorCode = ErrorCode::LOCK_PICKNUM_ERROR;
            return false;
        }
        if ($pickupNum > $lockOrder['stock']) {
            self::$errorCode = ErrorCode::LOCK_PICKNUM_MORE;
            return false;
        }
        //获取锁仓信息
        $field = 'id,current_price,stock,deposit_min_ratio,hold_time';
        $lockInfo = Lock::field($field)->where('id', $lockOrder['lock_id'])->findOrEmpty()->toArray();
        if (!$lockInfo) {
            self::$errorCode = ErrorCode::LOCK_NOT_EXIST;
            return false;
        }
        //判断价格是否有变动
        if ($currentPrice != $lockInfo['current_price']) {
            self::$errorCode = ErrorCode::OIL_PRICE_CHANGE;
            return false;
        }
        //判断账号余额
        $needPay = $pickupNum * $currentPrice - ($pickupNum/$lockOrder['buy_number']) * ($lockOrder['total_price'] * ($lockOrder['deposit_ratio'] / 100));
        if ($needPay > $company['amount_lock']) {
            self::$errorCode = ErrorCode::USER_SCORE_NOT_ENOUTH;
            return false;
        }
        //校验车辆信息参数
        $checkCarInfoParams = OrderService::gi()->checkCarInfoParams($carInfo);
        if (!$checkCarInfoParams) {
            return false;
        }

        $time = time();
        $outTradeNo = date('YmdHis') . substr($uid*($time-946656000),4,5).mt_rand(1000,9999);

        Db::startTrans();
        //所有参数校验通过，则生成订单
        try {
            //1、生成订单 2、扣减库存 3、车辆信息 4、扣减账号余额
            //1、生成订单
            $orderData = [
                'out_trade_no' => $outTradeNo,
                'uid' => $uid,
                'company_id' => $company['id'],
                'main_id' => $lockOrder['lock_id'],
                'oil_id' => $lockOrder['oil_id'],
                'price' => $currentPrice,
                'buy_number' => $pickupNum,
                'total_price' => $currentPrice * $pickupNum,
                'type' => OrderEnum::TYPE_LOCK,
                'status' => OrderEnum::STATUS_WAIT_VERIFY,
                'create_time' => $time,
                'lock_order_id' => $lockOrderId,
            ];
            $result = Order::create($orderData);
            //2、扣减库存
            LockOrder::where('id', $lockOrderId)->dec('stock', $pickupNum)->update();
            //3、车辆信息
            $data = [
                'order_id' => $result['id'],
                'driver_name' => $carInfo['driver_name'],
                'card_id' => $carInfo['card_id'],
                'mobile' => $carInfo['mobile'],
                'car_no' => $carInfo['car_no'],
            ];
            OrderCar::create($data);
            //4、扣减账号余额
            Company::where('id', $companyId)->dec('amount_procure', $needPay)->update();
            Db::commit();
            $ret = [
                'order_id' => $result['id']
            ];
            return $ret;
        } catch (\Exception $e) {
            Db::rollback();
            self::$errorCode = ErrorCode::SERVER_SERVER_ERROR;
            return false;
        }
    }

    /**
     * 锁仓交易记录（用户交易中的锁仓被其他用户购买的）
     *
     * @param $uid
     * @param $page
     * @param $limit
     */
    public function transactionRecord($uid, $page = 1, $limit = 10){
        if (!$uid) {
            self::$errorCode = ErrorCode::TOKEN_ERROR;
            return false;
        }

        $where = [
            ['uid', '=', $uid],
            ['selected', '=', 1],
        ];
        $field = 'id,amount_lock';
        $company = Company::field($field)->where($where)->findOrEmpty()->toArray();
        if (!$company) {
            self::$errorCode = ErrorCode::COMPANY_NOT_EXIST;
            return false;
        }
        $companyId = $company['id'];

        $where = [
            ['be_uid', '=', $uid],
            ['be_company_id', '=', $companyId]
        ];
        $field = 'out_trade_no,lock_id,oil_id,buy_number,total_price';
        $list = LockOrder::field($field)->where($where)->page($page, $limit)->order('id desc')->select()->toArray();
        $count = LockOrder::where($where)->count();
        if ($list) {
            //锁仓列表
            $lockIds = array_column($list, 'lock_id');
            $field = 'id,name,stock';
            $lockList = Lock::field($field)->whereIn('id', $lockIds)->select()->toArray();
            $lockList = $lockList ? array_column($lockList, null, 'id') : [];
            //油品列表
            $oidIds = array_column($list, 'oil_id');
            $field = 'id,model,type';
            $oilList = Oil::field($field)->whereIn('id', $oidIds)->select()->toArray();
            $oilList = $oilList ? array_column($oilList, null, 'id') : [];

            foreach ($list as &$item) {
                $item['name'] = isset($lockList[$item['lock_id']]) ? $lockList[$item['lock_id']]['name'] : '';
                $item['stock'] = isset($lockList[$item['lock_id']]) ? $lockList[$item['lock_id']]['stock'] : '';
                $item['model'] = isset($oilList[$item['oil_id']]) ? $oilList[$item['oil_id']]['model'] : '';
                $item['oil_type'] = isset($oilList[$item['oil_id']]) ? $oilList[$item['oil_id']]['type'] : '';
                unset($item['lock_id'], $item['oil_id']);
            }
        }

        $result = [
            'count' => $count,
            'total_page' => ceil($count/$limit),
            'list' => $list
        ];
        return $result;
    }

    /**
     * 购买详情页价格随时间的走势
     *
     * @param int    $lockId        锁仓ID
     * @param int    $oilId         油品ID
     * @param string $timeType      所选择的时间格式，日:day，周:week，月:month
     * @return false|array
     */
    public function priceTrend($lockId, $oilId, $timeType){
        if (!$lockId) {
            self::$errorCode = ErrorCode::LOCK_ID_NULL;
            return false;
        }
        //获取锁仓信息
        $lockInfo = Lock::field('id')->where('id', $lockId)->findOrEmpty()->toArray();
        if (!$lockInfo) {
            self::$errorCode = ErrorCode::LOCK_NOT_EXIST;
            return false;
        }
        //获取油的信息
        $where = [
            ['id', '=', $oilId],
        ];
        $oilInfo = Oil::field('id')->where($where)->findOrEmpty()->toArray();
        if (!$oilInfo) {
            self::$errorCode = ErrorCode::OIL_NOT_EXIST;
            return false;
        }
        if (!$timeType) {
            self::$errorCode = ErrorCode::OIL_TIME_TYPE_NULL;
            return false;
        }

        $timeTypes = OilEnum::getTimeDesc(true);
        if (!array_key_exists($timeType, $timeTypes)) {
            self::$errorCode = ErrorCode::OIL_TIME_TYPE_ERROR;
            return false;
        }

        $field = 'id,after_current_price current_price,open_price,create_time';
        $where = [
            ['lock_id', '=', $lockId],
            ['oil_id', '=', $oilId],
        ];
        $xTime = [];
        $yPrice = [];
        //日的价格走势
        if ($timeType == OilEnum::TIME_DAY) {
            $date = strtotime(date('Y-m-d'));
            $where[] = ['create_time', '>=', $date];
            $list = LockOilPriceLog::field($field)->withAttr('create_time',function ($value) {
                return $value;
            })->where($where)->order('id asc')->select()->toArray();
            if ($list) {
                foreach ($list as $item) {
                    array_push($yPrice, $item['current_price']);
                    $timeFormat = date('H:i', $item['create_time']);
                    array_push($xTime, $timeFormat);
                }
            }
        }
        //周的价格走势（本周每天的）
        if ($timeType == OilEnum::TIME_WEEK) {
            $date = date('Y-m-d', strtotime("this week"));
            $where[] = ['create_time', '>=', $date];
            $list = LockOilPriceLog::field($field)->withAttr('create_time',function ($value) {
                return $value;
            })->where($where)->group('week')->order('create_time asc')->select()->toArray();
            if ($list) {
                foreach ($list as $item) {
                    array_push($yPrice, $item['open_price']);
                    $timeFormat = date('m-d', $item['create_time']);
                    array_push($xTime, $timeFormat);
                }
            }
        }
        //月的价格走势（）
        if ($timeType == OilEnum::TIME_MONTH) {
            $date = strtotime(date('Y-m-01'));
            $where[] = ['create_time', '>=', $date];
            $list = LockOilPriceLog::field($field)->withAttr('create_time',function ($value) {
                return $value;
            })->where($where)->group('month_day')->order('create_time asc')->select()->toArray();
            if ($list) {
                foreach ($list as $item) {
                    array_push($yPrice, $item['open_price']);
                    $timeFormat = date('m-d', $item['create_time']);
                    array_push($xTime, $timeFormat);
                }
            }
        }
        $result = [
            'x_time' => $xTime,
            'y_price' => $yPrice
        ];
        return  $result;
    }
}
